<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { grantRolesApi } from '#/api/system/account';
import { getRoleListApi } from '#/api/system/role';

const emit = defineEmits<{
  success: [];
}>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 60,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        mode: 'multiple',
        labelField: 'name',
        valueField: 'id',
        api: getRoleListApi,
      },
      fieldName: 'roleIds',
      label: '角色',
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();
      const data = await formApi.getValues();
      try {
        await grantRolesApi(data.userId, data.roleIds);
        modalApi.close();
        message.success('授权成功');
        emit('success');
      } finally {
        modalApi.unlock();
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { userId, realname, roleIds } =
        modalApi.getData<Record<string, any>>();
      formApi.setValues({ userId, roleIds }, false);
      modalApi.setState({ title: `分配角色 (${realname})` });
    }
  },
});
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
